$(function(){
    var layer = layui.layer;

    $.ajaxSetup({
        layerLoading: -1,
        dataType: "json",
        // timeout: 3000,
        beforeSend: function(){
            this.layerLoading = layer.load(1, {
                shade: [0.2, "#fff"],
            })
        },
        complete: function(xhr, statusText){
            layer.close(this.layerLoading);
            if (statusText == "timeout") {
                msg("请求超时，请稍后重试");
            }
            if (xhr.status === 401) {
                msg("登录已过期，即将跳转到登录页...");
                var href = '/index/login';
                if (location.href.indexOf('index.php')) {
                    href = '/index.php' + href;
                }
                window.location.href = href;
            }
            // console.log(statusText);
            // console.log(xhr)
        }
    });


    /**
     * layer提示
     * @param text
     */
    function msg(text) {
        layer.msg(text);
    }

    /**
     * layer警告框
     * @param content
     * @param isSuccess
     */
    function layerAlert(content, isSuccess) {
        layer.alert(content, {
            icon: isSuccess ? 1 : 2,    //默认成功
        })
    }

    /**
     * layer询问框
     */
    function layerConfirm(content, callBack) {
        callBack = callBack || function(){};
        layer.confirm(content, {
            bnt: ["确定", "取消"]
        },callBack);
    }

    function submit_form($form) {
        // var $form = $(this).parents('form');
        ajax_submit($form)
            .done(function(resp){
                console.log(resp);
                if (!resp.error) {
                    msg(resp.message);
                    var pathArr = location.pathname.split("/");
                    pathArr[pathArr.length - 1] = "index.html";
                    location.href = pathArr.join("/");
                } else {
                    layerAlert(resp.message, false);
                }
            });
    }

    // ************ validate.js验证并提交表单 **************
    $.validator.setDefaults({
        // debug: true,
        errorClass: "error",
        submitHandler: function(form) {
            submit_form($(form))
        }
    });
    // 在表单提交页面定义validateConfig参数
    // var validateConfig = {
    //     rules: {
    //         firstname: "required",
    //             lastname: "required",
    //             username: {
    //             required: true,
    //             minlength: 2
    //         },
    //         password: {
    //             required: true,
    //             minlength: 5
    //         },
    //         confirm_password: {
    //             required: true,
    //             minlength: 5,
    //             equalTo: "#password"
    //         },
    //         email: {
    //             required: true,
    //             email: true
    //         },
    //         topic: {
    //             required: "#newsletter:checked",
    //             minlength: 2
    //         },
    //         agree: "required"
    //     },
    //     messages: {
    //         firstname: "请输入您的名字",
    //         lastname: "请输入您的姓氏",
    //         username: {
    //             required: "请输入用户名",
    //             minlength: "用户名必需由两个字符组成"
    //         },
    //         password: {
    //             required: "请输入密码",
    //             minlength: "密码长度不能小于 5 个字符"
    //         },
    //         confirm_password: {
    //             required: "请输入密码",
    //             minlength: "密码长度不能小于 5 个字符",
    //             equalTo: "两次密码输入不一致"
    //         },
    //         email: "请输入一个正确的邮箱",
    //         agree: "请接受我们的声明",
    //         topic: "请选择两个主题"
    //     }
    // };

    validateConfig = window.validateConfig || {};
    $("#save-form form").validate(validateConfig);

    /**
     * ajax 提交表单
     * @param $form
     * @returns {jQuery|*}
     */
    function ajax_submit($form) {
        return $.ajax({
            url: $form.data("action"),
            data: $form.serialize(),
            type: "POST",
        });
    }
    // ************ validate.js验证并提交表单/end **************

    // *********** 列表通用操作 *************
    // 编辑、批量选择、导出、删除等操作
    var $table = $(".list-container .table"),
        $form = $('#search-form');
    $('.list-container')
        .on("click", ".edit", function(){   //编辑
            _params = $table.data('params');
            let edit_url = _params.manage.edit_url+'?id='+$(this).data('id')
            location.href = edit_url;
        })
        .on("click", ".delete", function(){ //列表删除
            _params = $table.data('params');
            let delete_url = _params.manage.delete_url,
                id = $(this).data('id'),
                title = $(this).data('hint') || "确定要删除吗？";

            layerConfirm(title, function(){
                $.post(delete_url, {id: id}, function(res){
                   if (res.error) {
                       return layerAlert(res.message, false)
                   } else {
                       msg(res.message);

                   }
                });
            })
        });

    $('#search-form').on("click", ".search-btn",function(){
        let $form = $(this).parents("form");
        let url = location.pathname;
        $.get(url, $form.serialize(), function(res) {
            // console.log(res);
            if (res.error) {
                return msg(res.message);
            }
            renderTable(res);
        });
    });

    /**
     * 列表渲染
     * @param res
     */
    function renderTable(res) {
        let $table = $(".list-container .table"),
            columns = $table.data("columns")
            $tbody = $table.find("tbody"),
            _params = $table.data('params');
        $tbody.empty();
        if (res.data.list) {


            for (var i in res.data.list) {
                var _row = "<tr>";
                let data = res.data.list[i];
                // 选择框
                if (_params.has_checkbox) {
                    _row += "<td><input type='checkbox' data-id='"+data['id']+"'></td>";
                }

                columns.forEach(function(v){
                    _row += "<td>"+data[v]+"</td>";
                });

                // 操作
                if (_params.has_manage) {
                    let _manage = _params.manage;
                    // console.log(conf.manage)
                    var _td = "<td>";
                    if(_manage.edit) _td += '<button type="button" class="btn btn-xs btn-primary edit" data-id="'+data.id+'">编辑</button>';
                    if(_manage.delete) _td += '<button type="button" class="delete btn btn-xs btn-danger" data-id="'+data.id+'">删除</button>';

                    _td += "</td>";
                    _row += _td;
                }

                _row += "</tr>";

                $tbody.append(_row);
            }

        } else {
            var columnsNum = $table.find("thead tr td").count();
            $tbody.append('<tr><td colspan="' + columnsNum + '">暂无数据</td></tr>');
        }
    }

    // 全选，取消全选
    $(".select-all").on("click", function(){
        let $select = $(this);
        if ($select.prop("checked")) {
            $select.parents("th").find("span").text("取消全选");
            $('.table-list .table').find("tbody").find(":checkbox").prop("checked", true)
        } else {
            $select.parents("th").find("span").text("全选");
            $('.table-list .table').find("tbody").find(":checkbox").prop("checked", false)
        }
    });


    // 分页
    if ($(".content").find("#paginate").size()) {
        var laypage = layui.laypage;
        laypage.render({
            "elem": "paginate",
            "count": 124,
            "limit": 10,
            "limits": [10, 20, 50, 100],
            "curr": 1,
            "jump": function(obj, first) {
                //obj包含了当前分页的所有参数，比如：
                console.log(obj);

                let $form = $("#search-form");
                let url = location.pathname;
                var data = $form.serializeArray();

                var page = obj.curr;
                if (page > Math.ceil(obj.count/obj.curr)) {
                    page = obj.curr;
                }
                data.push({name: "page", value: page});
                data.push({name: "limit", "value": obj.limit});

                $.get(url, data , function(res) {
                    if (res.error) {
                        return msg(res.message);
                    }
                    renderTable(res);
                });

                //首次不执行
                // if(!first){
                //     //do something
                // }
            }
        });
    }
    // *********** 列表通用操作/end *************
});